﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WLYT.Application.Interfaces;
using WLYT.Common;
using WLYT.Domain.Model;
using WLYT.Repository;

namespace WLYT.Application.Services
{
    public class UserService : BaseService<User>, IUserService
    {
        public ISqlSugarRepository<User> UserRepository;
        public ISqlSugarRepository<Role> RoleRepository;
        public UserService(ISqlSugarRepository<User> userRepository, ISqlSugarRepository<Role> roleRepository) : base(userRepository)
        {
            UserRepository = userRepository;
            RoleRepository = roleRepository;
        }

        public async Task<bool> EditPassword(int id, string password, string newPassword)
        {
            var query = await GetByIdAsync(id);
            if (query.Password != StringHelper.MD5(password))
            {
                return false;
            }
            query.Password = StringHelper.MD5(newPassword);
            return await UpdateAsync(query);
        }

        public async Task<User> GetModelAsync(string name, string pwd)
        {
            string hashPassword = StringHelper.MD5(pwd);
            User model = await UserRepository.GetFirstAsync(p => p.UserNo == name && p.Password == hashPassword);
            return model;
        }

        public async Task<Tuple<IList<User>, int>> GetModelsByPageAsync(string search, int pageSize, int pageIndex)
        {
            var result = await GetPageListAsync(p => p.UserNo.Contains(search ?? ""), pageSize, pageIndex, p => p.Id);
            return result;
        }

        public async Task<bool> Save(User model)
        {
            var query = await GetByIdAsync(model.Id);
            if (query == null)
            {
                model.IsValid = true;
                model.CreateTime = DateTime.Now;
                model.Password = StringHelper.MD5("123456");
                return await AddAsync(model);
            }
            else
            {
                query.UserNo = model.UserNo;
                query.UserName = model.UserName;
                query.IsValid = model.IsValid;
                query.Memo = model.Memo;
                query.Roles = model.Roles;
                query.RoleId = model.RoleId;
                query.RoleName = (await RoleRepository.GetFirstAsync(p => p.Id == model.RoleId)).Name;
                return await UpdateAsync(query);
            }
        }
    }
}
